package cn.itcast.security;

import cn.hutool.core.collection.CollectionUtil;
import cn.itcast.UserService;
import cn.itcast.pojo.Permission;
import cn.itcast.pojo.Role;
import cn.itcast.pojo.User;
import com.alibaba.dubbo.config.annotation.Reference;

import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.*;
@Component
public class SpringSecurityUserService implements UserDetailsService {
 @Reference
   private UserService userService;


   //根据用户名查询用户信息
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    User user= userService.findByUsername(username);
    if (user==null){

        return null;
    }
       List<SimpleGrantedAuthority> authorities = new ArrayList<>();
    //根据用户查询权限
        Set<Role> roles = user.getRoles();
        if (CollectionUtil.isNotEmpty(roles)){
            for (Role role : roles) {
                Set<Permission> permissions = role.getPermissions();
                if (CollectionUtil.isNotEmpty(permissions)){
                    for (Permission permission : permissions) {
                        authorities.add(new SimpleGrantedAuthority(permission.getKeyword()));

                    }


                }

            }


        }
        return new org.springframework.security.core.userdetails.User(username,user.getPassword(),authorities);
    }
}

